from skillchallenge.models import *
import EventEngine
import CodeEngine
import random

class SkillChallengeEngine:
    
    random = random
    
    def create_test(self, skill, dc):
        return SkillTest.objects.create(skill=skill, dc=dc)
    
    def engage(self, event_id, object_id, char_id):
        test = SkillTest.objects.get(id=object_id)
        if test.test(Character.objects.get(id=char_id), self.random):
            Message.objects.create(text='(test succeeded)')
            if test.challenge:
                test.challenge.success_scored += 1
                test.challenge.save()
                if test.challenge.complete:
                    Message.objects.create(text='(test challenge: ' + str(test.challenge.name) + ' succeeded)')
        else:
            Message.objects.create(text='(test failed)')
            if test.challenge:
                test.challenge.failures_scored += 1
                test.challenge.save()
                if test.challenge.failed:
                    Message.objects.create(text='(test challenge: ' + str(test.challenge.name) + ' failed)')
        test.save()
    
    def create_challenge(self, name, succ, fail, keywords = None):
        return SkillChallenge.objects.create(name = name, success_need = succ, failures_limit = fail, 
                                             keywords = keywords)